'use client';

import React, { useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { PageContainer, ProTable, ProColumns } from '@ant-design/pro-components';
import { Button, Tag, Space, Tabs, Modal } from 'antd';
import { 
  EyeOutlined, 
  EditOutlined, 
  ReloadOutlined,
  DownloadOutlined,
  UserOutlined,
  UploadOutlined,
  DollarOutlined,
} from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { OrderInfo, OrderStatus, OrderSearchParams, ExperimentType, DemandOrder, PaymentMethod } from '@/types/order';
import { UserRole, UserStatus } from '@/types/user';
import { ORDER_STATUS_TEXT, ORDER_STATUS_COLOR, ORDER_STATUS_ACTIONS, COMMON_ACTIONS, TAB_CONFIG } from '@/constants/order';
import { useMessage } from '../../hooks/useMessage';
import { useOverlayManager } from '@/hooks/useOverlayManager';
import UserInfoModal from './components/UserInfoModal';
import ModifyOrderAmountModal from './components/ModifyOrderAmountModal';
import UploadDataModal from './components/UploadDataModal';



const OrdersPage: React.FC = () => {
  const router = useRouter();
  const actionRef = useRef<ActionType>(null);
  const [activeTab, setActiveTab] = useState('all');
  const message = useMessage();
  const { openOverlay } = useOverlayManager();
  const [userInfoModalVisible, setUserInfoModalVisible] = useState(false);
  const [selectedUserInfo, setSelectedUserInfo] = useState<{
    id: string;
    name: string;
    phone: string;
    email: string;
    department: string;
    university: string;
    userLevel: string;
    team: string;
    status: string;
    balance: number;
    idNumber: string;
    address: string;
  } | null>(null);

  // 模拟需求订单数据
  const mockDemandOrders: DemandOrder[] = [
    {
      id: 'demand-001',
      orderNumber: 'D000001',
      userId: 'user001',
      user: {
        id: 'user001',
        username: 'zhangteacher',
        realName: '张老师',
        phone: '18812341234',
        email: 'zhang@example.com',
        role: UserRole.LEVEL_3_USER,
        status: UserStatus.NORMAL,
        balance: 1500.00,
        isVerified: true,
        createdAt: '2025-01-01 00:00:00',
        updatedAt: '2025-03-28 10:30:00',
      },
      title: '材料表征综合测试需求',
      description: '需要对新型复合材料进行全面的物理化学性能表征',
      status: OrderStatus.PENDING_REVIEW,
      totalAmount: 2500.00,
      paymentMethod: PaymentMethod.TEAM_BALANCE,
      instrumentOrders: [
        {
          id: 'inst001',
          instrumentId: 'instrument001',
          instrumentName: '扫描电子显微镜',
          instrumentCategory: '微观形貌与结构表征',
          amount: 800.00,
          status: OrderStatus.PENDING_REVIEW,
          responsiblePerson: {
            id: 'resp001',
            name: '李工程师',
            phone: '13912345678',
          },
        },
      ],
      createdAt: '2025-03-28 10:30:00',
      updatedAt: '2025-03-28 15:20:00',
    },
    {
      id: 'demand-002',
      orderNumber: 'D000002',
      userId: 'user002',
      user: {
        id: 'user002',
        username: 'wangteacher',
        realName: '王教授',
        phone: '18823456789',
        email: 'wang@example.com',
        role: UserRole.LEVEL_2_USER,
        status: UserStatus.NORMAL,
        balance: 3000.00,
        isVerified: true,
        createdAt: '2025-01-01 00:00:00',
        updatedAt: '2025-03-28 10:30:00',
      },
      title: '新材料性能全面测试',
      description: '对新开发的复合材料进行全方位的性能测试，包括力学性能、热学性能、电学性能等',
      status: OrderStatus.PENDING_CONFIRMATION,
      totalAmount: 3200.00,
      paymentMethod: PaymentMethod.PERSONAL_BALANCE,
      instrumentOrders: [
        {
          id: 'inst002',
          instrumentId: 'instrument002',
          instrumentName: 'X射线衍射仪',
          instrumentCategory: '成分与结构分析',
          amount: 1200.00,
          status: OrderStatus.PENDING_CONFIRMATION,
          responsiblePerson: {
            id: 'resp002',
            name: '张工程师',
            phone: '13987654321',
          },
        },
        {
          id: 'inst003',
          instrumentId: 'instrument003',
          instrumentName: '万能试验机',
          instrumentCategory: '物理性能表征',
          amount: 2000.00,
          status: OrderStatus.PENDING_CONFIRMATION,
          responsiblePerson: {
            id: 'resp003',
            name: '赵工程师',
            phone: '13611111111',
          },
        },
      ],
      createdAt: '2025-03-27 14:20:00',
      updatedAt: '2025-03-28 09:15:00',
    },
  ];

  // 模拟普通订单数据
  const mockData: OrderInfo[] = [
    {
      id: '123456',
      orderNumber: '000001',
      experimentName: '送样申请',
      experimentType: ExperimentType.NORMAL,
      experimentLevel: '',
      instrumentName: '仪器名称',
      sampleInfo: '自带',
      orderAmount: 500.00,
      reservationTime: '2025-03-28 10:30-11:30',
      createdAt: '2025-03-28 10:30',
      createdBy: {
        id: '1',
        name: '18812341234(李老师)',
        phone: '18812341234'
      },
      responsiblePerson: {
        id: '1',
        name: '18812341234(李老师)',
        phone: '18812341234'
      },
      orderStatus: '待审核',
      status: OrderStatus.PENDING_REVIEW,
      orderType: 'sample_delivery', // 送样申请
    },
    {
      id: '123456-1',
      orderNumber: '000002',
      experimentName: '仪器预约-工程师操作',
      experimentType: ExperimentType.NORMAL,
      experimentLevel: '',
      instrumentName: '仪器名称',
      sampleInfo: '特殊情况',
      orderAmount: 295.00,
      reservationTime: '2025-03-28 10:30-11:30',
      createdAt: '2025-03-28 10:30',
      createdBy: {
        id: '1',
        name: '18812341234(李老师)',
        phone: '18812341234'
      },
      responsiblePerson: {
        id: '1',
        name: '18612341234(李老师)',
        phone: '18612341234'
      },
      orderStatus: '待确认',
      status: OrderStatus.PENDING_CONFIRMATION,
      orderType: 'engineer_operation', // 工程师操作
    },
    {
      id: '123456-2',
      orderNumber: '000003',
      experimentName: '仪器预约-自主操作',
      experimentType: ExperimentType.TRAINING,
      experimentLevel: '',
      instrumentName: '仪器名称',
      sampleInfo: '已寄出',
      orderAmount: 315.00,
      reservationTime: '2025-03-28 10:30-11:30',
      createdAt: '2025-03-28 10:30',
      createdBy: {
        id: '1',
        name: '18812341234(李老师)',
        phone: '18812341234'
      },
      responsiblePerson: {
        id: '1',
        name: '18612341234(李老师)',
        phone: '18612341234'
      },
      orderStatus: '实验中',
      status: OrderStatus.IN_PROGRESS,
      orderType: 'self_operation', // 自主操作
    },
    // 添加需求订单数据作为普通订单展示
    ...mockDemandOrders.map(demandOrder => ({
      id: demandOrder.id,
      orderNumber: demandOrder.orderNumber,
      experimentName: demandOrder.title,
      experimentType: ExperimentType.NORMAL,
      experimentLevel: '',
      instrumentName: `多仪器需求 (${demandOrder.instrumentOrders.length}个)`,
      sampleInfo: '多种情况',
      orderAmount: demandOrder.totalAmount,
      reservationTime: '需求订单',
      createdAt: demandOrder.createdAt,
      createdBy: {
        id: demandOrder.user.id,
        name: `${demandOrder.user.phone}(${demandOrder.user.realName})`,
        phone: demandOrder.user.phone
      },
      responsiblePerson: {
        id: 'multiple',
        name: '多个负责人',
        phone: ''
      },
      orderStatus: ORDER_STATUS_TEXT[demandOrder.status],
      status: demandOrder.status,
      orderType: 'demand_order', // 需求订单
    }))
  ];

  // 获取用户权限（模拟）
  const getCurrentUserRole = () => {
    // TODO: 从实际的用户状态获取
    return 'admin'; // admin, finance, operator, responsible_person
  };

  // 处理订单操作
  const handleOrderAction = async (record: OrderInfo, action: string) => {
    const confirmMessages: Record<string, string> = {
      '通过': '是否确定通过',
      '驳回': '是否确定驳回',
      '关闭订单': '是否确定关闭订单，关闭后该订单冻结余额/额度将退回',
      '结算': '是否确定结算',
      '上机': '是否确定上机',
      '下机': '是否确定下机',
      '退款': '是否确定退款，退款后订单金额将返回账户',
      '培训通过': '是否确定培训通过',
      '培训不通过': '是否确定培训不通过',
    };

    const confirmMessage = confirmMessages[action];
    if (confirmMessage) {
      Modal.confirm({
        title: '确认操作',
        content: confirmMessage,
        okText: '确定',
        cancelText: '取消',
        okButtonProps: {
          style: { backgroundColor: '#69cac3', borderColor: '#69cac3' }
        },
        onOk: async () => {
          try {
            // TODO: 调用实际API
            console.log('订单操作:', record.id, action);
            
            // 模拟状态变更
            // 模拟状态变更逻辑

            message.success(`${action}操作成功`);
            actionRef.current?.reload();
          } catch (error) {
            console.error('操作失败:', error);
            message.error(`${action}操作失败`);
          }
        }
      });
    }
  };

  // 修改订单金额
  const handleModifyAmount = async (record: OrderInfo) => {
    try {
      await openOverlay({
        name: "modify-amount-modal",
        Overlay: ModifyOrderAmountModal,
        props: {
          orderInfo: record,
          onSubmit: async (newAmount: number, remark: string) => {
            // TODO: 调用API修改订单金额
            console.log('修改订单金额:', { orderId: record.id, newAmount, remark });
            
            // 检查余额/额度是否充足的逻辑
            const balanceCheck = true; // 模拟检查结果
            if (!balanceCheck) {
              message.warning(`新增${newAmount - record.orderAmount}元费用，当前用户账户余额/额度不足，请联系用户充值或申请额度后继续操作`);
              return;
            }
            
            message.success('订单金额修改成功');
            actionRef.current?.reload();
          },
          onClose: () => {
            // 关闭回调
          },
        },
        openProp: "open",
      });
    } catch (error) {
      console.error('修改订单金额失败:', error);
      message.error('修改订单金额失败');
    }
  };

  // 上传数据
  const handleUploadData = async (record: OrderInfo) => {
    try {
      await openOverlay({
        name: "upload-data-modal",
        Overlay: UploadDataModal,
        props: {
          orderInfo: record,
          onSubmit: async (files: File[]) => {
            // TODO: 调用API上传数据
            console.log('上传数据:', { orderId: record.id, files });
            message.success('数据上传成功');
            actionRef.current?.reload();
          },
          onClose: () => {
            // 关闭回调
          },
        },
        openProp: "open",
      });
    } catch (error) {
      console.error('上传数据失败:', error);
      message.error('上传数据失败');
    }
  };

  // 查看用户信息
  const handleViewUserInfo = (userInfo: any) => {
    // 模拟完整的用户信息
    const fullUserInfo = {
      id: userInfo.id,
      name: userInfo.name,
      phone: userInfo.phone,
      email: `${userInfo.phone}@example.com`,
      department: '材料学院',
      university: '清华大学',
      userLevel: '3级用户',
      team: '松山湖团队（团队管理员）',
      status: 'normal' as const,
      balance: 1500.00,
      idNumber: '11010119900101****',
      address: '北京市海淀区清华大学',
    };
    
    setSelectedUserInfo(fullUserInfo);
    setUserInfoModalVisible(true);
  };

  // 查看订单详情
  const handleViewOrder = (record: OrderInfo) => {
    if (record.orderType === 'demand_order') {
      router.push(`/orders/demand/${record.id}`);
    } else {
      router.push(`/orders/${record.id}`);
    }
  };

  // 编辑订单
  const handleEditOrder = (record: OrderInfo) => {
    if (record.orderType === 'demand_order') {
      router.push(`/orders/demand/${record.id}?mode=edit`);
    } else {
      router.push(`/orders/${record.id}?mode=edit`);
    }
  };

  // 跳转到仪器排期页面
  const handleViewInstrumentSchedule = (instrumentName: string, instrumentId?: string) => {
    // TODO: 获取实际的仪器ID
    const mockInstrumentId = 'instrument-001';
    router.push(`/instruments/${mockInstrumentId}/schedule`);
  };

  // 跳转到样品邮寄页面
  const handleViewSampleShipping = (orderId: string) => {
    router.push(`/orders/${orderId}?tab=shipping`);
  };

  // 下载数据
  const handleDownloadData = (record: OrderInfo) => {
    // TODO: 实现数据下载逻辑
    console.log('下载数据:', record.id);
    message.success('数据下载开始');
  };

  // 重新提交订单
  const handleResubmitOrder = (record: OrderInfo) => {
    Modal.confirm({
      title: '确认重新提交',
      content: '是否确定重新提交该订单？',
      okText: '确定',
      cancelText: '取消',
      okButtonProps: {
        style: { backgroundColor: '#69cac3', borderColor: '#69cac3' }
      },
      onOk: async () => {
        try {
          // TODO: 调用API重新提交订单
          console.log('重新提交订单:', record.id);
          message.success('订单重新提交成功');
          actionRef.current?.reload();
        } catch (error) {
          console.error('重新提交失败:', error);
          message.error('重新提交失败');
        }
      }
    });
  };

  // 获取操作按钮
  const getActionButtons = (record: OrderInfo) => {
    const buttons = [];
    const userRole = getCurrentUserRole();
    const orderType = record.orderType || 'sample_delivery';
    const isTraining = record.experimentType === ExperimentType.TRAINING;

    // 查看按钮（所有人都可以查看）
    buttons.push(
      <Button
        key="view"
        type="link"
        size="small"
        icon={<EyeOutlined />}
        onClick={() => handleViewOrder(record)}
      >
        查看
      </Button>
    );

    // 需求订单的特殊处理
    if (orderType === 'demand_order') {
      // 需求订单只有查看和编辑权限
      // 管理员可以编辑需求订单整体的内容
      if (['admin', 'super_admin'].includes(userRole)) {
        buttons.push(
          <Button
            key="edit"
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditOrder(record)}
          >
            编辑
          </Button>
        );
      }
      // 仪器负责人可以编辑自己负责的仪器部分（在详情页面中处理）
      return buttons;
    }

    // 普通订单的编辑按钮（根据状态和权限）
    if ([OrderStatus.PENDING_REVIEW, OrderStatus.PENDING_CONFIRMATION, OrderStatus.WAITING_EXPERIMENT].includes(record.status)) {
      buttons.push(
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEditOrder(record)}
        >
          编辑
        </Button>
      );
    }

         // 根据订单状态获取可用操作
     const baseActions = (ORDER_STATUS_ACTIONS as any)[orderType]?.[record.status] || [];
     const availableActions = [...baseActions]; // 创建新数组，避免修改原数组
    
    // 培训相关特殊操作
    if (isTraining && record.status === OrderStatus.IN_PROGRESS) {
      const trainingActions = COMMON_ACTIONS.training_actions[record.status] || [];
      availableActions.push(...trainingActions);
    }

         // 添加状态操作按钮
     availableActions.forEach((action: string) => {
      // 财务专用操作权限检查
      if (COMMON_ACTIONS.finance_actions.includes(action) && !['admin', 'finance'].includes(userRole)) {
        return;
      }

      let buttonProps: any = {
        key: action,
        type: 'link',
        size: 'small',
        onClick: () => {
          if (action === '修改订单金额') {
            handleModifyAmount(record);
          } else if (action === '上传数据') {
            handleUploadData(record);
          } else if (action === '下载数据') {
            handleDownloadData(record);
          } else if (action === '重新提交') {
            handleResubmitOrder(record);
          } else {
            handleOrderAction(record, action);
          }
        }
      };

      // 设置按钮样式和图标
      if (action === '通过') {
        buttonProps.style = { color: '#52c41a' };
      } else if (['驳回', '关闭订单', '培训不通过'].includes(action)) {
        buttonProps.danger = true;
      } else if (action === '修改订单金额') {
        buttonProps.icon = <DollarOutlined />;
      } else if (action === '上传数据') {
        buttonProps.icon = <UploadOutlined />;
      }

      buttons.push(<Button {...buttonProps}>{action}</Button>);
    });

    return buttons;
  };

  // 表格列定义
  const columns: ProColumns<OrderInfo>[] = [
    {
      title: '订单编号',
      dataIndex: 'orderNumber',
      width: 120,
      fixed: 'left',
      search: true,
    },
    {
      title: '实验名称',
      dataIndex: 'experimentName',
      width: 200,
      ellipsis: true,
      search: false,
    },
    {
      title: '订单类型',
      dataIndex: 'orderType',
      width: 120,
      search: false,
      render: (_, record: OrderInfo) => {
        const typeMap: Record<string, string> = {
          'sample_delivery': '送样申请',
          'engineer_operation': '工程师操作',
          'self_operation': '自主操作',
          'demand_order': '需求订单',
        };
        return typeMap[record.orderType || ''] || record.orderType || '-';
      },
    },
    {
      title: '实验级别',
      dataIndex: 'experimentLevel',
      width: 100,
      search: false,
    },
    {
      title: '仪器名称',
      dataIndex: 'instrumentName',
      width: 150,
      search: true,
      render: (text: unknown, record: OrderInfo) => (
        <Button
          type="link"
          style={{ padding: 0, height: 'auto', color: '#69cac3' }}
          onClick={() => {
            if (record.orderType === 'demand_order') {
              router.push(`/orders/demand/${record.id}`);
            } else {
              const mockInstrumentId = 'instrument-001';
              router.push(`/instruments/${mockInstrumentId}/schedule`);
            }
          }}
        >
          {String(text)}
        </Button>
      ),
    },
    {
      title: '样品信息',
      dataIndex: 'sampleInfo',
      width: 100,
      search: false,
      render: (text: any, record: OrderInfo) => {
        if (text === '已寄出' || text === '特殊情况') {
          return (
            <Space>
              {text}
              <Button
                type="link"
                size="small"
                style={{ color: '#69cac3' }}
                onClick={() => handleViewSampleShipping(record.id)}
              >
                详情
              </Button>
            </Space>
          );
        }
        return text;
      },
    },
    {
      title: '订单金额',
      dataIndex: 'orderAmount',
      width: 100,
      render: (val) => `¥${val}`,
      search: false,
    },
    {
      title: '预约时间',
      dataIndex: 'reservationTime',
      width: 160,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 160,
      valueType: 'dateRange',
      search: true,
    },
    {
      title: '创建用户',
      dataIndex: ['createdBy', 'name'],
      width: 180,
      search: true,
      render: (text: any, record: OrderInfo) => (
        <Space>
          {text}
          <Button
            type="link"
            size="small"
            icon={<UserOutlined />}
            style={{ color: '#69cac3' }}
            onClick={() => handleViewUserInfo(record.createdBy)}
          >
            用户信息
          </Button>
        </Space>
      ),
    },
    {
      title: '负责人',
      dataIndex: ['responsiblePerson', 'name'],
      width: 180,
      search: true,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      width: 120,
      valueType: 'select',
      valueEnum: {
        [OrderStatus.PENDING_REVIEW]: { text: '待审核' },
        [OrderStatus.PENDING_CONFIRMATION]: { text: '待确认' },
        [OrderStatus.WAITING_EXPERIMENT]: { text: '待实验' },
        [OrderStatus.IN_PROGRESS]: { text: '实验中' },
        [OrderStatus.PENDING_SETTLEMENT]: { text: '待结算' },
        [OrderStatus.COMPLETED]: { text: '已完成' },
        [OrderStatus.TRAINING_PASSED]: { text: '完成（培训通过）' },
        [OrderStatus.TRAINING_FAILED]: { text: '完成（培训不通过）' },
        [OrderStatus.REJECTED]: { text: '已驳回' },
        [OrderStatus.CLOSED]: { text: '已关闭' },
        [OrderStatus.CANCELLED]: { text: '已取消' },
        [OrderStatus.REFUNDED]: { text: '已退款' },
      },
      render: (_, record: OrderInfo) => (
        <Tag color={ORDER_STATUS_COLOR[record.status]}>
          {ORDER_STATUS_TEXT[record.status]}
        </Tag>
      ),
      search: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 300,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <Space size="small" wrap>
          {getActionButtons(record)}
        </Space>
      ),
    },
  ];

  // 数据请求
  const request = async (params: OrderSearchParams & { current?: number; pageSize?: number }) => {
    console.log('请求参数:', params);
    
    let filteredData = [...mockData];
    
    // 根据Tab过滤
    if (activeTab !== 'all') {
      const tabConfig = TAB_CONFIG.find(tab => tab.key === activeTab);
      if (tabConfig?.status) {
        filteredData = filteredData.filter(item => item.status === tabConfig.status);
      } else if (activeTab === 'completed') {
        filteredData = filteredData.filter(item => 
          [OrderStatus.COMPLETED, OrderStatus.REJECTED, OrderStatus.CLOSED].includes(item.status)
        );
      } else if (activeTab === 'others') {
        filteredData = filteredData.filter(item => 
          [OrderStatus.CANCELLED, OrderStatus.REJECTED, OrderStatus.CLOSED, OrderStatus.REFUNDED].includes(item.status)
        );
      }
    }
    
    // 搜索过滤
    if (params.keyword) {
      filteredData = filteredData.filter(item => 
        item.orderNumber.includes(params.keyword!) ||
        item.createdBy.name.includes(params.keyword!)
      );
    }
    
    if (params.status) {
      filteredData = filteredData.filter(item => item.status === params.status);
    }

    return {
      data: filteredData,
      success: true,
      total: filteredData.length,
    };
  };

  return (
    <PageContainer>
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={TAB_CONFIG.map(tab => ({
          key: tab.key,
          label: tab.label,
          children: (
            <ProTable<OrderInfo>
              actionRef={actionRef}
              rowKey="id"
              search={{
                labelWidth: 'auto',
                defaultCollapsed: false,
                span: 6,
              }}
              form={{
                syncToUrl: true,
              }}
              toolbar={{
                search: {
                  onSearch: (value) => {
                    console.log('搜索:', value);
                  },
                  placeholder: '请输入订单编号',
                },
                actions: [
                  <Button 
                    key="create-demand" 
                    type="primary"
                    style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}
                    onClick={() => router.push('/orders/demand/create')}
                  >
                    创建需求订单
                  </Button>,
                  <Button key="reload" icon={<ReloadOutlined />}>
                    重置
                  </Button>,
                  <Button key="export" icon={<DownloadOutlined />}>
                    导出列表
                  </Button>,
                ],
              }}
              request={request}
              columns={columns}
              pagination={{
                defaultPageSize: 50,
                showSizeChanger: true,
              }}
              scroll={{ x: 1800 }}
              options={{
                density: true,
                fullScreen: true,
                setting: true,
              }}
            />
          ),
        }))}
      />
      
      {/* 用户信息弹窗 */}
      <UserInfoModal
        open={userInfoModalVisible}
        onClose={() => {
          setUserInfoModalVisible(false);
          setSelectedUserInfo(null);
        }}
        userInfo={selectedUserInfo}
      />
    </PageContainer>
  );
};

export default OrdersPage; 